/**
 * Created by machan on 2017/4/3.
 */
const constants = require('../../../common/Constants.js');
const umfDialog = require('../../../utils/UmfDialog.js');
const netWork_utils = require('../../../http/NetworkUtils.js');

const PhotoTags = {
    BUS_PAYEE_ID_P: 'payeeCardPhotoFront',
    BUS_PAYEE_ID_N: 'payeeCardPhotoCon',
    BUS_PERSON_ID_P: 'categoryCardPhotoFront',
    BUS_PERSON_ID_N: 'categoryCardPhotoCon',
    BUS_SIGN: 'shopSignPhotoFront',
    BUS_INNER: 'shopSignPhotoCon',
    BUS_LICENCE: 'busiLicensePhoto',
    BUS_AUTH: 'authCertPhoto'
};

export function photoData() {
    //店铺ID
    this.storeId = '';
    //店铺类型
    this.busType = constants.BusTypes.PERSONAL;
    //店铺简称
    this.busNickName = '';
    //经营者
    this.busPerson = '';
    //是否是授权的场合
    this.isAuthorize = true;
    //缓存管理
    this.cacheManager = '';
    //模块化照片模型
    this.viewData = [];

    this.initPhotoInfoPage = (basisPage, params)=> {
        let photoInfoData = {
            payeeCardPhotoFront: params.payeeCardPhotoFront?decodeURIComponent(params.payeeCardPhotoFront):"",
            payeeCardPhotoCon: params.payeeCardPhotoCon?decodeURIComponent(params.payeeCardPhotoCon):"",
            categoryCardPhotoFront: params.categoryCardPhotoFront?decodeURIComponent(params.categoryCardPhotoFront):"",
            categoryCardPhotoCon: params.categoryCardPhotoCon?decodeURIComponent(params.categoryCardPhotoCon):"",
            shopSignPhotoFront: params.shopSignPhotoFront?decodeURIComponent(params.shopSignPhotoFront):"",
            shopSignPhotoCon: params.shopSignPhotoCon?decodeURIComponent(params.shopSignPhotoCon):"",
            busiLicensePhoto: params.busiLicensePhoto?decodeURIComponent(params.busiLicensePhoto):"",
            authCertPhoto: params.authCertPhoto?decodeURIComponent(params.authCertPhoto):""
        };
        let photoData = this.init(params.storeId, params.payeeName, params.storeMan, params.storeType, params.isAuthorize)
            .initUrls(photoInfoData);

        basisPage.setData({
            photoData: photoData
        });
    };

    this.init = (storeId, busNickName, busPerson, busType, isAuthorize) => {
        //初始化
        this.storeId = storeId;
        this.busNickName = busNickName;
        this.busPerson = busPerson;
        this.busType = busType;
        this.isAuthorize = busPerson && parseInt(isAuthorize) === 1;
        // this.cacheManager = new cacheUtils.cacheManager();
        // this.cacheManager.init(storeId, constants.STORAGE_FUNC.PHOTO_INFO);

        this.viewData = _createViewDatas(this);
        return this;
    };

    this.initUrls = (object)=> {
        for (let key of Object.keys(object)) {
            let value = object[key];

            if (value) {
                for (let viewItem of this.viewData) {
                    if (viewItem.photoTag === key) {
                        viewItem.setSuccessState().setPhoto(value);
                        this.updateViewData(viewItem);
                    }
                }
            }
        }
        return this;
    };

    this.updateViewData = (newViewData) => {
        let id = newViewData.photoTag;
        for (let item in this.viewData) {
            if (id === this.viewData[item].photoTag) {
                this.viewData[item] = newViewData;
                break;
            }
        }
    };

    this.deleteViewData = (tag)=> {
        for (let index in this.viewData) {
            if (tag === this.viewData[index].photoTag) {
                this.viewData.splice(index,1);
                break;
            }
        }
    };

    this.getDataFromTag = (tag)=> {
        for (let index in this.viewData) {
            if (tag === this.viewData[index].photoTag) {
                return this.viewData[index];
            }
        }
    };
}

/**
 * 点击上传事件
 * @param page
 * @param photoTag
 * @param photoData
 */
export function tapAdd(page, photoTag, photoData) {
    let item = photoData.getDataFromTag(photoTag);
    _processUpload(page, item, photoData);
}

/**
 * 点击预览图片
 * @param page
 * @param photoTag
 * @param photoData
 */
export function tapPhoto(page, photoTag, photoData) {
    let item = photoData.getDataFromTag(photoTag);

    wx.previewImage({
        current: item.photoUrl, // 当前显示图片的http链接
        urls: [item.photoUrl] // 需要预览的图片http链接列表
    });
}

/**
 * 点击错误事件
 * @param page
 * @param photoTag
 * @param photoData
 */
export function tapError(page, photoTag, photoData) {
    umfDialog.showAll("抱歉,图片上传失败", "重新选择", "重试", ()=> {
        //重试
        let item;
        for (let index in photoData.viewData) {
            if (photoTag === photoData.viewData[index].photoTag) {
                item = photoData.viewData[index];
                break;
            }
        }

        let filePath = item.photoUrl;
        _upload(page, item, photoData, filePath);

    }, ()=> {
        //重新选择
        let item;
        for (let index in photoData.viewData) {
            if (photoTag === photoData.viewData[index].photoTag) {
                item = photoData.viewData[index];
                break;
            }
        }
        _processUpload(page, item, photoData);
    });
}

/**
 * 点击事例
 * @param photoTag
 * @param photoData
 */
export function tapExample(photoTag, photoData) {
    let item = photoData.getDataFromTag(photoTag);

    wx.previewImage({
        current: item.exampleUrl, // 当前显示图片的http链接
        urls: [item.exampleUrl] // 需要预览的图片http链接列表
    });
}

/**
 * 点击下一步
 * @param photoData
 */
export function tapNext(photoData, onSuccess) {
    let message = checkError(photoData);
    if (message) {
        umfDialog.show(message);
        return;
    }

    //请求服务器接口
    _requestSubmit(photoData, onSuccess);
}

export function checkError(photoData) {
    let errItem;
    for (let index in photoData.viewData) {
        let item = photoData.viewData[index];
        if (!item.hasUpload) {
            errItem = item;
            break;
        }
    }

    if (errItem) {
        let message;
        if (errItem.isInit) {
            message = '请上传 ' + errItem.name + " " + errItem.title + '照片';
        } else if (errItem.loading) {
            message = errItem.title + '照片上传中,请等待上传完成';
        } else if (errItem.hasError) {
            message = errItem.title + '上传失败，请重新上传';
        } else {
            message = errItem.title + '照片未知错误，请重新上传';
        }
        umfDialog.show(message);
        return message;
    }
    return '';
}

function _createViewDatas(photoData) {
    let viewDatas = [];
    if (photoData.busNickName) {
        let bus_payee_P = new _viewDataConfig(PhotoTags.BUS_PAYEE_ID_P)
          .init(photoData.busNickName, " 身份证正面", "需清晰完整", "https://m.soopay.net/c/static/jjxqgbqs");
        viewDatas.push(bus_payee_P);

        let bus_payee_N = new _viewDataConfig(PhotoTags.BUS_PAYEE_ID_N)
          .init(photoData.busNickName, " 身份证反面", "需清晰完整", "https://m.soopay.net/c/static/tozogssx");
        viewDatas.push(bus_payee_N);
    }

    if (photoData.busType === constants.BusTypes.COMPANY && photoData.isAuthorize) {
        let bus_person_P = new _viewDataConfig(PhotoTags.BUS_PERSON_ID_P)
          .init(photoData.busPerson, " 身份证正面", "需清晰完整", "https://m.soopay.net/c/static/jjxqgbqs");
        viewDatas.push(bus_person_P);

        let bus_person_N = new _viewDataConfig(PhotoTags.BUS_PERSON_ID_N)
          .init(photoData.busPerson, " 身份证反面", "需清晰完整", "https://m.soopay.net/c/static/tozogssx");
        viewDatas.push(bus_person_N);
    }

    let signD = new _viewDataConfig(PhotoTags.BUS_SIGN)
      .init("", "店铺招牌", "需清晰完整的招牌", "https://m.soopay.net/c/static/elcmcmfi");
    viewDatas.push(signD);

    let innerD = new _viewDataConfig(PhotoTags.BUS_INNER)
      .init("", "店铺内景", "需能明显体现店内经营内容", "https://m.soopay.net/c/static/gsutubgo");
    viewDatas.push(innerD);

    if (photoData.busType === constants.BusTypes.COMPANY) {
        let licenseD = new _viewDataConfig(PhotoTags.BUS_LICENCE)
          .init("", "营业执照", "营业执照正面清晰照片", "https://m.soopay.net/c/static/wocxdewc");
        viewDatas.push(licenseD);
        if (photoData.isAuthorize) {
            let authD = new _viewDataConfig(PhotoTags.BUS_AUTH)
              .init("", "授权函", "营业执照法人授权收款人", "https://m.soopay.net/c/static/kuqmivbm");
            viewDatas.push(authD);
        }
    }
    return viewDatas;
}

function _viewDataConfig(photoTag) {
    //位置标记
    this.photoTag = photoTag;
    //是否是初始状态
    this.isInit = true;
    //是否上传完成
    this.hasUpload = false;
    //是否出错
    this.hasError = false;
    //是否正在上传
    this.loading = false;

    //姓名
    this.name
    //标题
    this.title = '';
    //描述
    this.dec = '';
    //相片路径
    this.photoUrl = '';
    //服务器相片路径
    this.remoteUrl = '';
    //事例图
    this.exampleUrl = '';

    this.init = (name, title, dec, exampleUrl) => {
        this.name = name;
        this.title = title;
        this.dec = dec;
        this.exampleUrl = exampleUrl;
        this.isInit = true;
        this.loading = false;
        this.hasUpload = false;
        this.hasError = false;
        return this;
    };

    this.setLoadingState = () => {
        this.isInit = false;
        this.loading = true;
        this.hasUpload = false;
        this.hasError = false;
        return this;
    };

    this.setErrorState = ()=> {
        this.isInit = false;
        this.loading = false;
        this.hasUpload = false;
        this.hasError = true;
        return this;
    };

    this.setSuccessState = ()=> {
        this.isInit = false;
        this.loading = false;
        this.hasUpload = true;
        this.hasError = false;
        return this;
    };

    this.setPhoto = (photoUrl) => {
        this.photoUrl = photoUrl;
        return this;
    };

    // this.cachePhoto = (photoData)=> {
    //     photoData.cacheManager.cacheFunc({[this.photoTag]: this.remoteUrl});
    // }
}

function _processUpload(page, item, photoData) {
    wx.chooseImage({
        count: 1,
        sizeType: ['compressed'], //压缩图
        success: function (res) {
            let tempFilePaths = res.tempFilePaths;

            _upload(page, item, photoData, tempFilePaths[0]);
        }
    });

}

function _upload(page, item, photoData, filePath) {
    //上传中
    item.setLoadingState()
        .setPhoto(filePath);
    photoData.updateViewData(item);
    page.setData({
        photoData: photoData
    });

    netWork_utils.buildRequest(constants.Interfaces.FUNC_UPLOAD_IMG, {storeId: photoData.storeId, img: item.photoTag}, {
        doHttpSucess: function (response) {
            if (constants.RetCodes.SUCCESS === response.retCode) {
                //上传成功
                item.remoteUrl = response.imgUrl;
                item.setSuccessState()
                    .setPhoto(filePath)
                    //缓存
                    // .cachePhoto(photoData);
                photoData.updateViewData(item);
                page.setData({
                    photoData: photoData
                });
                return true;
            }
              //上传失败
              item.setErrorState()
                .setPhoto(filePath);
              photoData.updateViewData(item);
              page.setData({
                photoData: photoData
              });
            
            return false;
        }
        ,
        doHttpFailure: function (errorData) {
            //上传失败
            item.setErrorState()
                .setPhoto(filePath);
            photoData.updateViewData(item);
            page.setData({
                photoData: photoData
            });
            return true;
        }
        ,
        doComplete: function () {
            return false;
        }
    }, false).upload(filePath);
}

/**
 * 请求接口
 * @param viewData
 * @private
 */
function _requestSubmit(photoData, onSuccess) {
    // let params = _getParams(viewData);
    netWork_utils.buildRequest(constants.Interfaces.FUNC_SUBMIT_IMG, {storeId: photoData.storeId}, {
        doHttpSucess: (response)=> {
            if (constants.RetCodes.SUCCESS === response.retCode) {
                onSuccess();
                return true;
            }
            return false;
        }
    }).send();
}

function _getParams(viewData) {
    let params = {
        payeeCardPhotoFront: '',
        payeeCardPhotoCon: '',
        categoryCardPhotoFront: '',
        categoryCardPhotoCon: '',
        shopSignPhotoFront: '',
        shopSignPhotoCon: '',
        busiLicensePhoto: '',
        authCertPhoto: '',
    };
    for (let index in viewData) {
        let item = viewData[index];
        if (item.photoTag === PhotoTags.BUS_PAYEE_ID_P) {
            params.payeeCardPhotoFront = item.remoteUrl;
        } else if (item.photoTag === PhotoTags.BUS_PAYEE_ID_N) {
            params.payeeCardPhotoCon = item.remoteUrl;
        } else if (item.photoTag === PhotoTags.BUS_PERSON_ID_P) {
            params.categoryCardPhotoFront = item.remoteUrl;
        } else if (item.photoTag === PhotoTags.BUS_PERSON_ID_N) {
            params.categoryCardPhotoCon = item.remoteUrl;
        } else if (item.photoTag === PhotoTags.BUS_SIGN) {
            params.shopSignPhotoFront = item.remoteUrl;
        } else if (item.photoTag === PhotoTags.BUS_INNER) {
            params.shopSignPhotoCon = item.remoteUrl;
        } else if (item.photoTag === PhotoTags.BUS_LICENCE) {
            params.busiLicensePhoto = item.remoteUrl;
        } else if (item.photoTag === PhotoTags.BUS_AUTH) {
            params.authCertPhoto = item.remoteUrl;
        }
    }
    return params;
}